<template>
  <div class="coach-info-container">
    <!-- 页面标题栏 -->
    <div class="page-header">
      <el-button
          type="default"

          @click="handleGoBack"
          class="back-btn"
      >
        <el-icon><arrow-left /></el-icon>
        返回
      </el-button>
      <h2>教练信息管理</h2>
      <div class="header-actions">
        <el-button
            type="primary"

            @click="openPasswordDialog"
            :disabled="!userStore.user || isRefreshing"
            class="password-btn"
        >
          <el-icon><Lock /></el-icon>
          修改密码
        </el-button>
        <el-button
            type="primary"
            @click="openEditDialog"
            :disabled="!userStore.user || isRefreshing"
        >
          <el-icon><Edit /></el-icon>
          编辑信息
        </el-button>
      </div>
    </div>
    <el-dialog
        v-model="isPasswordDialogOpen"
        title="修改密码"
        width="400px"
        :before-close="handlePasswordDialogClose"
    >
      <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordFormRules"
          label-width="100px"
          size="medium"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入原密码"
              show-password
              maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码（6-20位）"
              show-password
              maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
              maxlength="20"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handlePasswordDialogClose">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm">确认修改</el-button>
      </template>
    </el-dialog>
    <!-- 加载状态 -->
    <el-loading
        v-if="isRefreshing"
        text="正在加载教练信息..."
        fullscreen
    ></el-loading>

    <!-- 教练信息卡片 -->
    <el-card
        v-if="userStore.user"
        class="info-card"
        shadow="hover"
    >
      <div class="info-grid">
        <!-- 头像与证件照区域 -->
        <div class="avatar-section">
          <!-- 添加 square-avatar 类用于自定义方形样式 -->
          <el-avatar
              :size="120"
              :src="userStore.user.photo || defaultAvatar"
              class="user-avatar square-avatar"
          >
            {{ getAvatarPlaceholder(userStore.user.realName || userStore.user.username) }}
          </el-avatar>
          <p class="user-name">{{ userStore.user.realName || '未设置姓名' }}</p>
          <p class="user-role">角色：{{ getUserRoleText(userStore.user.userType) }}</p>
        </div>


        <!-- 详细信息列表 -->
        <div class="detail-section">
          <el-descriptions
              title="基本信息"
              border
              :column="2"
              size="small"
          >
            <el-descriptions-item label="用户名">{{ userStore.user.username || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ userStore.user.gender === 'male' ? '男' : userStore.user.gender === 'female' ? '女' : '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="年龄">{{ userStore.user.age || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ userStore.user.phone || '未绑定' }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ userStore.user.email || '未绑定' }}</el-descriptions-item>
            <el-descriptions-item label="所属校区">{{ userStore.user.campusId?.name || '未知校区' }}</el-descriptions-item>

            <!-- 教练特有字段（不可修改） -->
            <el-descriptions-item label="教练等级">
              <el-tag type="primary">
                {{ formatCoachLevel(userStore.user.level) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="教龄">
              {{ userStore.user.teachingYears ? `${userStore.user.teachingYears} 年` : '未设置' }}
            </el-descriptions-item>

            <el-descriptions-item label="账号状态">
              <el-tag :type="userStore.getAccountStatus() === '正常' ? 'success' : 'danger'">
                {{ userStore.getAccountStatus() }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ userStore.formatCreateTime() }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 无数据提示 -->
    <div class="empty-tip" v-else-if="!isRefreshing">
      <el-empty description="教练信息加载失败，请点击刷新重试"></el-empty>
    </div>

    <!-- 编辑信息弹窗 -->
    <el-dialog
        v-model="isEditDialogOpen"
        title="修改教练信息"
        :width="['300px', '500px', '600px']"
        :before-close="handleDialogClose"
    >
      <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="100px"
          size="medium"
      >

        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="editForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
              oninput="this.value = this.value.replace(/[^0-9]/g, '')"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>

          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
              v-model="editForm.age"
              placeholder="可选，未设置则留空"
              type="number"
              min="18"
              max="65"
              @input="handleAgeInput"
          ></el-input>
        </el-form-item>

        <!-- 不可修改字段 -->

      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick, computed } from 'vue'
// 修复2：从图标库导入 Loading 图标（替换 Spinner）
import { ElMessage, ElEmpty, ElLoading, ElTag, ElImage } from 'element-plus'
import { Edit, ArrowLeft, Refresh, Picture, Loading,Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import {useAuthStore} from "@/stores/auth.js";
const authStore = useAuthStore()
// 初始化依赖
const userStore = useUserStore()
const router = useRouter()
const isRefreshing = ref(false)
const isEditDialogOpen = ref(false)
const editFormRef = ref(null)

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369e630459aa77654b212c.png'

// 教龄计算属性
const teachingYearsValue = computed(() => {
  if (!userStore.user || !userStore.user.teachingYears) {
    return ''
  }
  return `${userStore.user.teachingYears} 年`
})

// 处理证件照URL
const getValidIdPhotoUrl = () => {
  if (!userStore.user || !userStore.user.idPhoto) {
    return ''
  }
  const idPhotoPath = userStore.user.idPhoto
  if (isValidUrl(idPhotoPath)) {
    return idPhotoPath
  }
  return ''
}

// 验证URL格式
const isValidUrl = (url) => {
  try {
    new URL(url)
    return true
  } catch (e) {
    return false
  }
}

// 编辑表单数据
const editForm = reactive({
  realName: '',
  phone: '',
  email: '',
  gender: '',
  age: null
})

// 表单验证规则
const editFormRules = reactive({
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度需在2-20字符之间', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur', required: false }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur', required: false }
  ],
  age: [
    {
      type: 'number',
      message: '请输入有效年龄（数字）',
      trigger: 'blur',
      required: false,
      transform: (value) => {
        return value === '' || value === undefined ? null : Number(value)
      }
    },
    {
      min: 18,
      max: 65,
      message: '年龄需在18-65之间',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (value === null || value === undefined || value === '') {
          callback()
        } else if (value < 18 || value > 65) {
          callback(new Error('年龄需在18-65之间'))
        } else {
          callback()
        }
      }
    }
  ]
})

// 页面挂载时加载数据
onMounted(() => {
  refreshUserInfo()
})

// 监听用户信息变化
watch(
    () => userStore.user,
    (newUser) => {
      if (newUser) {
        syncUserToForm()
      }
    },
    { deep: true }
)

// 刷新用户信息
const refreshUserInfo = async () => {
  isRefreshing.value = true
  try {
    await userStore.fetchCurrentUserInfo()
    if (userStore.user) {
      ElMessage.success('教练信息刷新成功！')
    } else {
      throw new Error('未获取到有效教练信息')
    }
  } catch (err) {
    userStore.user = null
    ElMessage.error(`刷新失败：${err.message || '服务器异常'}`)
  } finally {
    isRefreshing.value = false
  }
}

// 同步用户信息到表单
const syncUserToForm = () => {
  const user = userStore.user
  editForm.realName = user.realName || ''
  editForm.phone = user.phone || ''
  editForm.email = user.email || ''
  editForm.gender = user.gender || ''
  editForm.age = user.age === undefined || user.age === '' || user.age === null ? null : Number(user.age)
}

// 打开编辑弹窗
const openEditDialog = () => {
  syncUserToForm()
  isEditDialogOpen.value = true
  nextTick(() => {
    editFormRef.value?.$el.querySelector('input').focus()
  })
}

// 关闭编辑弹窗
const handleDialogClose = () => {
  isEditDialogOpen.value = false
  nextTick(() => {
    editFormRef.value?.resetFields()
  })
}

// 提交修改
const submitEditForm = async () => {
  const isValid = await editFormRef.value.validate().catch(() => false)
  if (!isValid) return

  try {
    await userStore.updateUserInfo(editForm)
    Object.assign(userStore.user, {
      realName: editForm.realName,
      phone: editForm.phone,
      email: editForm.email,
      gender: editForm.gender,
      age: editForm.age
    })
    handleDialogClose()
    ElMessage.success('教练信息修改成功！')
  } catch (err) {
    ElMessage.error(`修改失败：${err.message || '服务器异常'}`)
  }
}

// 返回按钮
const handleGoBack = () => {
  if (window.history.length > 1) {
    router.back()
  } else {
    router.push('/dashboard/coach')
  }
}

// 头像占位符
const getAvatarPlaceholder = (name) => {
  if (!name) return '教'
  return name.charAt(0).toUpperCase()
}

// 角色文本转换
const getUserRoleText = (userType) => {
  const roleMap = {
    'student': '学生',
    'coach': '教练',
    'admin': '管理员'
  }
  return roleMap[userType] || '未知角色'
}

// 处理年龄输入
const handleAgeInput = (value) => {
  if (value === '' || value === undefined) {
    editForm.age = null
  }
}
const formatCoachLevel = (level) => {
  if (!level) return '未评定'
  const levelMap = {
    'senior': '高级',
    'intermediate': '中级',
    'junior': '初级'
  }
  return levelMap[level] || level
}
const isPasswordDialogOpen = ref(false)
const passwordFormRef = ref(null)

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordFormRules = reactive({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度需在6-20位之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度需在8-20位之间', trigger: 'blur' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
      message: '密码需包含字母和数字和特殊字符',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 打开密码修改弹窗
const openPasswordDialog = () => {
  isPasswordDialogOpen.value = true
  nextTick(() => {
    passwordFormRef.value?.resetFields()
  })
}

// 关闭密码修改弹窗
const handlePasswordDialogClose = () => {
  isPasswordDialogOpen.value = false
  nextTick(() => {
    passwordFormRef.value?.resetFields()
  })
}

// 提交密码修改
const submitPasswordForm = async () => {
  const isValid = await passwordFormRef.value.validate().catch(() => false)
  if (!isValid) return

  try {
    // 调用修改密码的API
    await userStore.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    ElMessage.success('密码修改成功，请重新登录')
    handlePasswordDialogClose()

    // 密码修改成功后重新登录
    setTimeout(() => {
      userStore.logout()
      router.push('/')
      authStore.clearAuth()
      window.location.replace('/')
    }, 1500)

  } catch (err) {
    ElMessage.error(`修改失败：${err.message || '服务器异常'}`)
  }
}
</script>

<style scoped lang="scss">
/* 样式与之前保持一致 */
.coach-info-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px - 40px);
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.back-btn {
  border-color: #dcdfe6;
  color: #606266;
  &:hover {
    border-color: #c0c4cc;
    color: #303133;
  }
}

.header-actions {
  display: flex;
  gap: 10px;
}

.refresh-btn {
  border-color: #dcdfe6;
  color: #606266;
  &:hover {
    border-color: #c0c4cc;
    color: #303133;
  }
}

.info-card {
  background-color: #fff;
  border-radius: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 3fr;
  gap: 30px;
  padding: 20px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.user-avatar {
  border: 4px solid #f0f2f5;
  background-color: #e6f7ff;

  // 移除原有圆角（如果存在）
  border-radius: 0 !important;
}
// 方形头像专属样式（如果需要额外调整）
.square-avatar {
  // 确保完全方形，移除所有圆角
  border-radius: 0;
  // 可选：添加更明显的边框
  border-width: 2px;
  border-style: solid;
  border-color: #e5e7eb;

  // 当没有头像图片时，占位文本的容器也保持方形
  &:not(.el-avatar--icon) {
    border-radius: 0;
  }
}
.user-name {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.user-role {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 证件照样式 */
.id-photo-section {
  margin-top: 20px;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin: 0;
  align-self: flex-start;
}

.id-photo {
  width: 100%;
  height: 200px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background-color: #f9fafb;
}

.image-loading {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9fafb;
  color: #409eff; /* 加载图标颜色 */
}

.image-placeholder {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  background-color: #f9fafb;
  border: 1px dashed #d1d5db;
  border-radius: 4px;
  gap: 8px;

  p {
    margin: 0;
    font-size: 14px;
  }
}

.hint-text {
  font-size: 12px;
  color: #9ca3af;
  margin: 0;
  text-align: center;
}

.detail-section {
  padding: 10px 0;
}

.el-descriptions {
  --el-descriptions-title-color: #1f2937;
  --el-descriptions-label-color: #4b5563;
  --el-descriptions-content-color: #111827;
}

.el-descriptions-item {
  padding: 12px 8px;
}

.empty-tip {
  margin: 50px auto;
  text-align: center;
}

/* 编辑弹窗中不可修改字段样式 */
:deep(.el-form-item.is-disabled .el-input__wrapper) {
  background-color: #f9fafb;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .detail-section {
    padding: 0;
  }

  .el-descriptions {
    column-count: 1;
  }
}
</style>